<?php

require_once('../../config/maptrick.conf.php');
require_once(SITE_ROOT . 'lib/PHT.php');
require_once(SITE_ROOT . 'class/bean/Country.class.php');
require_once(SITE_ROOT . 'class/bean/Training.class.php');
require_once(SITE_ROOT . 'class/bean/TrainingType.class.php');
require_once(SITE_ROOT . 'class/db/DBCountry.class.php');
require_once(SITE_ROOT . 'class/db/DBTraining.class.php');

try {
	if ($_GET["pass"] != SCRIPT_PWD) die("Incorrect password");

	$HT = new CHPPConnection(CONSUMERKEY, CONSUMERSECRET);
	$HT->setOauthToken(USERTOKEN);
	$HT->setOauthTokenSecret(USERTOKENSECRET);
	
	$dbcountry = new DBCountry();
	$countries = $dbcountry->getCountries("countryID");
	
	$dbtraining = new DBTraining();
	
	foreach ($countries as $country) {
		$htTrainingStats = $HT->getTrainingStats($country->getCountryID());
		
		$trainings = new ArrayObject();
		
		for ($i=1; $i<=$htTrainingStats->getNumberTrainingType(); $i++) {
			$htTrainingType = $htTrainingStats->getTrainingType($i);
			$trainingtype = new TrainingType($htTrainingType->getType());
			$training = new Training($trainingtype, $country, time(), $htTrainingType->getNumberOfTeams(), $htTrainingType->getPercentageOfTeams());
			$trainings->append($training);
		}
		
		$dbtraining->saveTrainings($trainings);
		
		$HT->clearTrainingStats($country->getCountryID());
		
		echo date('Y-m-d', time()) . " -  Training for " . $country->getName() . " successfully updated<br />";
	}	
	echo date('Y-m-d', time()) . " -  Training for all countries successfully updated";
}
catch (Exception $e) {
	echo $e->getMessage();
}

?>